package com.atguigu.lease.common.jwt;

import com.atguigu.lease.common.exception.EnumException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author 86188
 * @version v1.0
 * @project ShangTingApartment
 * @Date 2025/7/12 16:17
 * @company []
 * @description
 */

public class JwtUtil {
    private static long tokenExpiration = 6* 60 *60*1000;
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("M0PKKI6pYGVWWfDZw90a0lTpGYX1d4AQ".getBytes());

    public static String createToToken(Long userId,String username){
        String token = Jwts.builder().
                setSubject("USER_INFO").
                setExpiration(new Date(System.currentTimeMillis()+tokenExpiration)).
                claim("userId",userId).
                claim("username",username).
                signWith(tokenSignKey).
                compressWith(CompressionCodecs.GZIP).
                compact();
        return token;
    }
    public static Claims parseToken(String token){
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().
                    setSigningKey(tokenSignKey).build().parseClaimsJws(token);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            throw new EnumException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new EnumException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
